package com.fishingwithme.domain.anybiting;


import com.fishingwithme.infrastructure.dtos.anybiting.CircleMessageDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

@Component
public class CircleMessageClientImpl implements CircleMessageClient {

    @Autowired
    private CircleMessageService messageService;

    @Override
    public boolean saveMessage(CircleMessageDTO messageDTO) {
        try {
            messageService.saveMessage(messageDTO);
            return true;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public int sendBatchMessages(Iterable<CircleMessageDTO> messages) {
        int successCount = 0;
        for (CircleMessageDTO message : messages) {
            if (saveMessage(message)) {
                successCount++;
            }
        }
        return successCount;
    }

    @Override
    public boolean sendCompressedMessage(byte[] compressedData, Long circleId) {
        try {
            // 解压数据
            byte[] decompressedData = decompress(compressedData);
            // 这里可以解析解压后的数据并转换为消息对象
            // 为简化示例，直接返回 true
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 压缩数据
     */
    public static byte[] compress(String data) throws IOException {
        ByteArrayOutputStream bos = new ByteArrayOutputStream(data.length());
        GZIPOutputStream gzip = new GZIPOutputStream(bos);
        gzip.write(data.getBytes());
        gzip.close();
        byte[] compressed = bos.toByteArray();
        bos.close();
        return compressed;
    }

    /**
     * 解压数据
     */
    public static byte[] decompress(byte[] compressedData) throws IOException {
        ByteArrayInputStream bis = new ByteArrayInputStream(compressedData);
        GZIPInputStream gis = new GZIPInputStream(bis);
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len;
        while ((len = gis.read(buffer)) != -1) {
            bos.write(buffer, 0, len);
        }
        gis.close();
        bis.close();
        bos.close();
        return bos.toByteArray();
    }
}